package com.puppy.aop;

import com.puppy.mapper.OperateLogMapper;
import com.puppy.pojo.OperateLog;
import com.puppy.utils.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class LoggingAspect {

//    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // 定义切点，拦截所有public方法，并且方法名以add、delete、update、select开头
//    @Pointcut("execution(public * com..service.*.*(..)) && " +
//            "(execution(* *add*(..)) || execution(* *delete*(..)) || " +
//            "execution(* *update*(..)) || execution(* *select*(..)))")
//    public void loggingPointcut() {
//    }
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.puppy.anno.Log)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Long begin = System.currentTimeMillis();
        Object result = pjp.proceed();
        Long end = System.currentTimeMillis();
        Long costTime = end - begin;
        //构造日志实体
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(ThreadLocalUtils.getCurrentLocal());//操作人,从线程变量中获得-Integer类型
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(pjp.getTarget().getClass().getName());
        operateLog.setMethodName(pjp.getSignature().getName());
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));
        operateLog.setReturnValue(result != null ? result.toString() : "void");
        operateLog.setCostTime(costTime);
        //保存日志
        operateLogMapper.insert(operateLog);
        log.info("日志对象：{}", operateLog);
        return result; //返回目标操作的结果
    }
}
    